package section6_6;

import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * Created by Hyman on 2017/6/15.
 *
 * 使用线程安全可遍历映射
 */
public class Main {

    public static void main(String[] args) {

        ConcurrentSkipListMap<String, Contact> map = new ConcurrentSkipListMap<>();

        Thread[] threads = new Thread[25];
        int counter = 0;

        for(char i='A'; i<'Z'; i++) {
            Task task = new Task(String.valueOf(i), map);
            threads[counter] = new Thread(task);
            threads[counter].start();
            counter++;
        }

        for(int i=0; i<25; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 输出映射的大小
        System.out.printf("Main: Size of the map: %d\n", map.size());

        Map.Entry<String, Contact> element = map.firstEntry();
        Contact contact = element.getValue();
        System.out.printf("Main: First Entry: %s: %s\n", contact.getName(), contact.getPhone());


        // 输出最后一个映射条目
        element = map.lastEntry();
        contact = element.getValue();
        System.out.printf("Main: Last Entry: %s: %s\n", contact.getName(), contact.getPhone());

        // 输出映射的字集
        System.out.printf("Main: Submap from A1996 to B1002: \n");
        ConcurrentNavigableMap<String, Contact> submap = map.subMap("A1996", "B1002");
        do {

            element = submap.pollFirstEntry();
            if(element != null) {
                contact = element.getValue();
                System.out.printf("%s: %s\n", contact.getName(), contact.getPhone());
            }
        } while(element != null);

    }

}
